<template>
  <el-card class="box-card">
    <div class="text item">
      <h2>视频搜索</h2>
    </div>

    <el-form ref="searchForm" inline>
      <!-- 时间区间选择 -->
      <el-form-item label="选择日期区间">
        <el-date-picker
          v-model="searchCriteria.dateRange"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          range-separator="至"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>

      <!-- 名字输入 -->
      <el-form-item label="视频名">
        <el-input v-model="searchCriteria.name" placeholder="输入视频名" />
      </el-form-item>

      <!-- 搜索按钮 -->
      <el-form-item>
        <el-button type="primary" @click="searchVideos">搜索</el-button>
      </el-form-item>
    </el-form>

    <!-- 视频列表 -->
    <el-table :data="formattedData" style="width: 100%">
      <el-table-column prop="name" label="视频名" width="280" />
      <el-table-column prop="formattedDateTime" label="日期时间" width="280" />
      <el-table-column prop="description" label="描述" width="280" />
      <el-table-column label="操作" width="240">
        <template #default="scope">
          <el-button type="text" @click="goToVideo(scope.row)">播放</el-button>
          <el-button type="text" @click="confirmDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页控件 -->
    <el-pagination
      :current-page="pagination.currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper, ->, slot"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <template #slot>
        <span style="margin-left: 10px;">共 {{ totalPages }} 页</span>
      </template>
    </el-pagination>
  </el-card>
</template>

<script>
import moment from 'moment-timezone'
import { MessageBox, Message } from 'element-ui'
export default {
  data() {
    return {
      searchCriteria: {
        dateRange: [],
        name: ''
      },
      // 存储搜索结果
      videoList: [],
      // 分页
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    }
  },
  computed: {
    formattedData() {
      return this.videoList.map(item => ({
        video: item.video,
        name: item.name,
        size: item.size,
        id: item.id,
        path: item.path,
        media_root: item.media_root,
        description: item.description,
        formattedDateTime: item.upload_date
      }))
    }
  },
  created() {
    // this.list_all()
    this.searchVideos()
  },
  methods: {
    // 搜索视频
    searchVideos() {
      const { startDate, endDate, name, currentPage, pageSize } = this.paginationParameters()
      const param = {
        startDate: startDate,
        endDate: endDate,
        name: name,
        currentPage: currentPage,
        pageSize: pageSize
      }
      if (param.name == null) {
        param.name = ''
      }
      console.log(param)
      this.$store.dispatch('video/searchvideo', param)
        .then((response) => {
          // 请求成功，处理后端返回的数据
          const responseData = response.pageInfo
          this.videoList = responseData.list
          this.pagination.total = responseData.total // 假设后端返回总条目数
          Message({
            type: 'success',
            message: 'success',
            duration: 1000
          })
        })
        .catch((error) => {
          // 请求失败，处理错误
          console.error('Error:', error)
        })
    },
    // 播放视频
    goToVideo(video) {
      console.log('跳转到视频页面', video)
      // this.$router.push({ name: 'playVideo', query: { name: video.name, url: decodeURI(video.video), size: video.size, media_root: video.media_root }})
      this.$router.push({ name: 'playVideo', query: { name: video.name, url: video.path }})
      console.log('跳转到视频页面成功', video)
    },
    // 确认删除弹窗
    confirmDelete(video) {
      MessageBox.confirm('此操作将永久删除该视频, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteVideo(video)
      }).catch(() => {
        // 用户点击了取消
        console.log('删除操作已取消')
      })
    },
    // 删除视频
    deleteVideo(video) {
      const param = {
        id: video.id
      }
      console.log('删除视频', video)
      // 发送到deletevideo处理
      this.$store.dispatch('video/deletevideo', param)
        .then((response) => {
          // 请求成功，处理后端返回的数据
          console.log('删除视频成功')
          Message({
            type: 'success',
            message: '删除成功!'
          })
          // 重新搜索以刷新列表
          this.searchVideos()
        })
        .catch((error) => {
          // 请求失败，处理错误
          Message({
            type: 'error',
            message: '删除失败: ' + error.message
          })
          console.error('Error:', error)
        })
    },
    formatDateTime(isoDateTime) {
      return moment(isoDateTime).tz('Asia/Shanghai').format('YYYY-MM-DD')
    },
    handleSizeChange(newSize) {
      this.pagination.pageSize = newSize
      this.searchVideos()
    },
    handleCurrentChange(newPage) {
      this.pagination.currentPage = newPage
      this.searchVideos()
    },
    paginationParameters() {
      const [startDate, endDate] = this.searchCriteria.dateRange
      let start = null
      let end = null
      // 把endDate加一天

      if (startDate == null) {
        start = ''
      } else {
        start = this.formatDateTime(startDate)
      }
      if (endDate == null) {
        end = ''
      } else {
        // 把endDate加一天,选中某一天，出来的结果要包括那天。
        const dateObj = new Date(endDate)
        dateObj.setDate(dateObj.getDate() + 1)
        const endData_temp = dateObj.toISOString().split('T')[0]
        end = this.formatDateTime(endData_temp)
      }
      if (this.searchCriteria.name == null) {
        this.searchCriteria.name = ''
      }
      return {
        startDate: start,
        endDate: end,
        name: this.searchCriteria.name,
        currentPage: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      }
    },
    totalPages() {
      return Math.ceil(this.pagination.total / this.pagination.pageSize)
    }
  },
  list_all() {

  }
}
</script>

  <style scoped>
  .box-card {
    margin: 20px;
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
  }
  .text.item {
    text-align: center;
  }
  </style>
